<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="97px">
      <el-form-item label="诗词标题" prop="title">
        <el-input
            v-model="queryParams.title"
            placeholder="请输入诗词标题"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="诗词作者" prop="author">
        <el-input
            v-model="queryParams.author"
            placeholder="请输入诗词作者"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作者所属朝代" prop="dynasty">
        <el-select v-model="queryParams.dynasty" placeholder="请选择作者所属朝代" clearable>
          <el-option
              v-for="dict in cul_destinies"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['manage:poem:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['manage:poem:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['manage:poem:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['manage:poem:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="poemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" prop="id"/>
      <el-table-column label="诗词标题" align="center" prop="title"/>
      <el-table-column label="诗词作者" align="center" prop="author"/>
      <el-table-column label="诗词内容" align="center" prop="content" show-overflow-tooltip/>
      <el-table-column label="作者所属朝代" align="center" prop="dynasty">
        <template #default="scope">
          <dict-tag :options="cul_destinies" :value="scope.row.dynasty"/>
        </template>
      </el-table-column>
      <el-table-column label="字数" align="center" prop="wordCount" />
      <el-table-column label="标题类型" align="center" prop="titleType">
        <template #default="scope">
          <dict-tag :options="poem_type" :value="scope.row.titleType"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['manage:poem:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['manage:poem:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改诗词管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="poemRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="诗词标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入诗词标题" />
        </el-form-item>
        <el-form-item label="诗词作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入诗词作者" />
        </el-form-item>
        <el-form-item label="诗词内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="作者所属朝代" prop="dynasty">
          <el-select v-model="form.dynasty" placeholder="请选择作者所属朝代">
            <el-option
                v-for="dict in cul_destinies"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="字数" prop="wordCount">
          <el-input v-model="form.wordCount" placeholder="请输入字数" />
        </el-form-item>
        <el-form-item label="标题类型" prop="titleType">
          <el-select v-model="form.titleType" placeholder="请选择标题类型">
            <el-option
                v-for="dict in poem_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-divider content-position="center">诗词类型管理信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddPoemType">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeletePoemType">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="poemTypeList" :row-class-name="rowPoemTypeIndex" @selection-change="handlePoemTypeSelectionChange" ref="poemType">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="诗词类型" prop="type" width="150">
            <template #default="scope">
              <!--              <el-input v-model="scope.row.type" placeholder="请输入诗词类型" />-->
              <el-select v-model="scope.row.name" placeholder="请选择诗词类型" @change="changePoemType(scope.row)">
                <el-option
                    v-for="dict in poemTypeListSelect"
                    :key="dict.name"
                    :label="dict.name"
                    :value="dict.name"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="体裁类型" prop="formType" width="150">
            <template #default="scope">
              <!--              <el-input v-model="scope.row.formType" placeholder="请输入体裁类型" />-->
              <el-select v-model="scope.row.value" placeholder="请选择体裁类型列表">
                <el-option
                    v-for="value in checkValueList"
                    :key="value"
                    :label="value"
                    :value="value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Poem">
import { listPoem, getPoem, delPoem, addPoem, updatePoem } from "@/api/manage/poem";

const { proxy } = getCurrentInstance();
const { poem_type, cul_destinies } = proxy.useDict('poem_type', 'cul_destinies');

const poemList = ref([]);
const poemTypeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedPoemType = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    author: null,
    content: null,
    dynasty: null,
  },
  rules: {
    title: [
      { required: true, message: "诗词标题不能为空", trigger: "blur" }
    ],
    author: [
      { required: true, message: "诗词作者不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "诗词内容不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/**-- 定义诗词管理的诗词类型和体裁类型静态数据 ---*/
const poemTypeListSelect = ref([
  {name: '古体诗', value: ["四言诗", "五言古诗", "七言古诗", "乐府诗", "杂言诗"]},
  {name: '近体诗', value: ["五言绝句", "七言绝句", "五言律诗", "七言律诗"]},
  {name: '词类(字数)', value: ["小令(≤58字)", "中调(59-90字)", "长调(≥91字)"]},
  {name: '词类(段落)', value: ["单调(多用于小令)", "双调(分上下两阕)", "三叠(三段)"]},
  {name: '曲类', value: ["散曲", "小令", "带过曲"]},
])
// 存储当前选中类型列表的数组
const checkValueList = ref([]);

// 定义改变类型时更新当前选择的体裁类型
function changePoemType(row) {
//   清空当前行value
  row.value = []
//   根据选中的type查找静态数据的value
  checkValueList.value = poemTypeListSelect.value.find(item => item.name === row.name).value;

}

/** 查询诗词管理列表 */
function getList() {
  loading.value = true;
  listPoem(queryParams.value).then(response => {
    poemList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    title: null,
    author: null,
    content: null,
    createTime: null,
    updateTime: null,
    dynasty: null,
    wordCount: null,
    titleType: null
  };
  poemTypeList.value = [];
  proxy.resetForm("poemRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加诗词管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getPoem(_id).then(response => {
    form.value = response.data;
    poemTypeList.value = response.data.poemTypeList;
    poemTypeList.value.forEach(item => {
      item.name = item.type
      console.log(item.name)
      item.value = item.formType
      console.log(item.formType)
    })

    open.value = true;
    title.value = "修改诗词管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["poemRef"].validate(valid => {
    if (valid) {
      form.value.poemTypeList = poemTypeList.value;
      // 将口味列表的value通过json工具类转化为字符串
      form.value.poemTypeList.forEach(item => {
        item.type = item.name
        item.formType = item.value
      })

      if (form.value.id != null) {
        updatePoem(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPoem(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除诗词管理编号为"' + _ids + '"的数据项？').then(function() {
    return delPoem(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 诗词类型管理序号 */
function rowPoemTypeIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 诗词类型管理添加按钮操作 */
function handleAddPoemType() {
  let obj = {};
  obj.type = "";
  obj.formType = "";
  poemTypeList.value.push(obj);
}

/** 诗词类型管理删除按钮操作 */
function handleDeletePoemType() {
  if (checkedPoemType.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的诗词类型管理数据");
  } else {
    const poemTypes = poemTypeList.value;
    const checkedPoemTypes = checkedPoemType.value;
    poemTypeList.value = poemTypes.filter(function(item) {
      return checkedPoemTypes.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handlePoemTypeSelectionChange(selection) {
  checkedPoemType.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/poem/export', {
    ...queryParams.value
  }, `poem_${new Date().getTime()}.xlsx`)
}

getList();
</script>
